{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9734faad",
   "metadata": {},
   "source": [
    "### 10.2.2 对乳腺癌数据集进行K近邻分类"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "3b6821fc",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入必要的库\n",
    "import numpy as np \n",
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.metrics import accuracy_score,confusion_matrix,classification_report\n",
    "\n",
    "# 读取数据集\n",
    "data = pd.read_csv('data/breast_cancer_data.csv')\n",
    "\n",
    "# 数据预处理\n",
    "X = data.drop(['id', 'diagnosis', 'Unnamed: 32'], axis=1)  # 特征\n",
    "y = data['diagnosis']  # 目标变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "7f334e8c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 划分训练集和测试集\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "# 特征标准化\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "69aa37fa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "标准化后的训练集特征均值：\n",
      " [-0. -0. -0.  0. -0. -0. -0.  0.  0.  0.  0.  0.  0.  0. -0. -0.  0. -0.\n",
      " -0.  0. -0. -0. -0.  0. -0. -0. -0. -0.  0.  0.]\n",
      "标准化后的训练集特征标准差:\n",
      " [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.\n",
      " 1. 1. 1. 1. 1. 1.]\n",
      "标准化后的测试集特征均值：\n",
      " [ 0.01  0.12  0.02  0.01  0.22  0.07 -0.01  0.08  0.01  0.03  0.06  0.13\n",
      "  0.02  0.03  0.08 -0.04 -0.14 -0.08 -0.02 -0.05  0.04  0.12  0.02  0.03\n",
      "  0.18  0.05 -0.06  0.03 -0.03  0.02]\n",
      "标准化后的测试集特征标准差:\n",
      " [0.98 1.04 1.   0.96 1.03 1.03 1.02 1.09 0.99 0.89 0.89 1.08 0.88 0.8\n",
      " 0.91 0.8  0.63 0.9  1.06 0.71 1.02 1.06 1.03 1.02 0.93 1.07 0.98 1.03\n",
      " 0.89 1.06]\n"
     ]
    }
   ],
   "source": [
    "print('标准化后的训练集特征均值：\\n',np.round(np.mean(X_train_scaled,axis=0),2))\n",
    "print('标准化后的训练集特征标准差:\\n',np.round(np.std(X_train_scaled,axis=0),2))\n",
    "print('标准化后的测试集特征均值：\\n',np.round(np.mean(X_test_scaled,axis=0),2))\n",
    "print('标准化后的测试集特征标准差:\\n',np.round(np.std(X_test_scaled,axis=0),2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "f7be3456",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 构建 K 近邻分类器\n",
    "knn_classifier = KNeighborsClassifier(n_neighbors=5)\n",
    "\n",
    "# 拟合模型\n",
    "knn_classifier.fit(X_train_scaled, y_train)\n",
    "\n",
    "# 进行预测\n",
    "y_pred = knn_classifier.predict(X_test_scaled)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "93778365",
   "metadata": {},
   "outputs": [],
   "source": [
    "?confusion_matrix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "fd01a9a9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "准确率：0.95\n",
      "混淆矩阵：\n",
      " [[68  3]\n",
      " [ 3 40]]\n",
      "分类报告：\n",
      "               precision    recall  f1-score   support\n",
      "\n",
      "           B       0.96      0.96      0.96        71\n",
      "           M       0.93      0.93      0.93        43\n",
      "\n",
      "    accuracy                           0.95       114\n",
      "   macro avg       0.94      0.94      0.94       114\n",
      "weighted avg       0.95      0.95      0.95       114\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 评估模型性能\n",
    "accuracy = accuracy_score(y_test, y_pred)\n",
    "conf_matrix = confusion_matrix(y_test, y_pred)\n",
    "report = classification_report(y_test, y_pred)\n",
    "\n",
    "# 打印结果\n",
    "print(f'准确率：{accuracy:.2f}')\n",
    "print('混淆矩阵：\\n', conf_matrix)\n",
    "print('分类报告：\\n', report)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a7c0933a",
   "metadata": {},
   "source": [
    "### 10.2.3 使用网格搜索寻找最佳邻居数量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "8e4a2913",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "最优邻居数量：7\n",
      "最优模型在测试集上的准确率：0.95\n",
      "最优模型的分类报告：\n",
      "               precision    recall  f1-score   support\n",
      "\n",
      "           B       0.96      0.96      0.96        71\n",
      "           M       0.93      0.93      0.93        43\n",
      "\n",
      "    accuracy                           0.95       114\n",
      "   macro avg       0.94      0.94      0.94       114\n",
      "weighted avg       0.95      0.95      0.95       114\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from sklearn.model_selection import GridSearchCV\n",
    "\n",
    "# 构建 K 近邻分类器\n",
    "knn_classifier = KNeighborsClassifier()\n",
    "\n",
    "# 设置需要搜索的参数范围\n",
    "param_grid = {'n_neighbors': [3, 5, 7, 9, 11, 13, 15]}\n",
    "\n",
    "# 创建 GridSearchCV 对象\n",
    "grid_search = GridSearchCV(knn_classifier, param_grid, cv=10)\n",
    "\n",
    "# 对模型进行拟合（在训练集上进行交叉验证）\n",
    "grid_search.fit(X_train_scaled, y_train)\n",
    "\n",
    "# 输出最优参数\n",
    "best_neighbors = grid_search.best_params_['n_neighbors']\n",
    "print(f'最优邻居数量：{best_neighbors}')\n",
    "\n",
    "# 输出最优模型在测试集上的性能\n",
    "best_model = grid_search.best_estimator_\n",
    "y_pred_best = best_model.predict(X_test_scaled)\n",
    "\n",
    "accuracy_best = accuracy_score(y_test, y_pred_best)\n",
    "report_best = classification_report(y_test, y_pred_best)\n",
    "\n",
    "# 打印结果\n",
    "print(f'最优模型在测试集上的准确率：{accuracy_best:.2f}')\n",
    "print('最优模型的分类报告：\\n', report_best)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83df7f06",
   "metadata": {},
   "source": [
    "### 10.4.2 对乳腺癌数据集进行支持向量机分类"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "2d2f4d68",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入必要的库\n",
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.svm import SVC\n",
    "from sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n",
    "\n",
    "# 读取数据集\n",
    "data = pd.read_csv('data/breast_cancer_data.csv')\n",
    "\n",
    "# 数据预处理\n",
    "X = data.drop(['id', 'diagnosis', 'Unnamed: 32'], axis=1)  # 特征\n",
    "y = data['diagnosis']  # 目标变量\n",
    "# 将标签编码为二进制，B为0，M为1\n",
    "y = y.map({'B': 0, 'M': 1})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "0fc0f009",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 将数据集划分为训练集和测试集\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "# 特征标准化\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "b48cbcfa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-2 {color: black;background-color: white;}#sk-container-id-2 pre{padding: 0;}#sk-container-id-2 div.sk-toggleable {background-color: white;}#sk-container-id-2 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-2 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-2 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-2 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-2 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-2 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-2 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-2 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-2 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-2 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-2 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-2 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-2 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-2 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-2 div.sk-item {position: relative;z-index: 1;}#sk-container-id-2 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-2 div.sk-item::before, #sk-container-id-2 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-2 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-2 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-2 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-2 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-2 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-2 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-2 div.sk-label-container {text-align: center;}#sk-container-id-2 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-2 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-2\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>SVC(kernel=&#x27;linear&#x27;)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-2\" type=\"checkbox\" checked><label for=\"sk-estimator-id-2\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">SVC</label><div class=\"sk-toggleable__content\"><pre>SVC(kernel=&#x27;linear&#x27;)</pre></div></div></div></div></div>"
      ],
      "text/plain": [
       "SVC(kernel='linear')"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 创建并训练支持向量机模型\n",
    "svm_model = SVC(kernel='linear', C=1.0)\n",
    "svm_model.fit(X_train_scaled, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "d2da3ba8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 在测试集上进行预测\n",
    "y_pred = svm_model.predict(X_test_scaled)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "dcfb5258",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "模型准确率: 0.956140350877193\n",
      "\n",
      "分类报告:\n",
      "               precision    recall  f1-score   support\n",
      "\n",
      "           0       0.97      0.96      0.96        71\n",
      "           1       0.93      0.95      0.94        43\n",
      "\n",
      "    accuracy                           0.96       114\n",
      "   macro avg       0.95      0.96      0.95       114\n",
      "weighted avg       0.96      0.96      0.96       114\n",
      "\n",
      "\n",
      "混淆矩阵:\n",
      " [[68  3]\n",
      " [ 2 41]]\n"
     ]
    }
   ],
   "source": [
    "# 计算模型准确率\n",
    "accuracy = accuracy_score(y_test, y_pred)\n",
    "print(f'模型准确率: {accuracy}')\n",
    "# 打印分类报告和混淆矩阵\n",
    "print('\\n分类报告:\\n', classification_report(y_test, y_pred))\n",
    "print('\\n混淆矩阵:\\n', confusion_matrix(y_test, y_pred))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec31ee9c",
   "metadata": {},
   "source": [
    "### 10.4.3 使用网格搜索寻找最优支持向量机分类器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "4b0b3219",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Best Parameters:  {'C': 1, 'gamma': 'scale', 'kernel': 'rbf'}\n",
      "Best Cross-Validated Accuracy: 0.98\n",
      "\n",
      "Best Model Accuracy: 0.9824561403508771\n",
      "\n",
      "Best Model Confusion Matrix:\n",
      " [[71  0]\n",
      " [ 2 41]]\n",
      "\n",
      "Best Model Classification Report:\n",
      "               precision    recall  f1-score   support\n",
      "\n",
      "           0       0.97      1.00      0.99        71\n",
      "           1       1.00      0.95      0.98        43\n",
      "\n",
      "    accuracy                           0.98       114\n",
      "   macro avg       0.99      0.98      0.98       114\n",
      "weighted avg       0.98      0.98      0.98       114\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 导入必要的库\n",
    "from sklearn.model_selection import GridSearchCV\n",
    "\n",
    "# 定义参数网格\n",
    "param_grid = {\n",
    "    'C': [0.1, 1, 10, 100],        # 正则化参数\n",
    "    'kernel': ['linear', 'rbf'],  # 核函数类型\n",
    "    'gamma': ['scale', 'auto'],   # 核函数的系数（仅对'rbf'核有效）\n",
    "}\n",
    "\n",
    "# 创建支持向量机模型\n",
    "svm_model = SVC()\n",
    "\n",
    "# 创建GridSearchCV对象\n",
    "grid_search = GridSearchCV(svm_model, param_grid, cv=5, scoring='accuracy')\n",
    "\n",
    "# 执行网格搜索\n",
    "grid_search.fit(X_train_scaled, y_train)\n",
    "\n",
    "# 输出最优参数组合和对应的准确率\n",
    "print(\"Best Parameters: \", grid_search.best_params_)\n",
    "print(\"Best Cross-Validated Accuracy: {:.2f}\".format(grid_search.best_score_))\n",
    "\n",
    "# 使用最优参数组合的模型在测试集上进行评估\n",
    "best_svm_model = grid_search.best_estimator_\n",
    "y_pred_best = best_svm_model.predict(X_test_scaled)\n",
    "\n",
    "# 输出最优模型的性能指标\n",
    "accuracy_best = accuracy_score(y_test, y_pred_best)\n",
    "conf_matrix_best = confusion_matrix(y_test, y_pred_best)\n",
    "classification_rep_best = classification_report(y_test, y_pred_best)\n",
    "\n",
    "print(\"\\nBest Model Accuracy:\", accuracy_best)\n",
    "print(\"\\nBest Model Confusion Matrix:\\n\", conf_matrix_best)\n",
    "print(\"\\nBest Model Classification Report:\\n\", classification_rep_best)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
